﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KacincisinProject.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult ImageKaydet()
        {
            var image = Request.Params["image"];
            if (string.IsNullOrEmpty(image)) return View();

            var imageContent = Convert.FromBase64String(image);
            if (imageContent == null) return View();

            var save = Request.Params["save"];
            var name = Request.Params["name"];
            var type = Request.Params["type"];
            if (!string.IsNullOrEmpty(save) &&
                !string.IsNullOrEmpty(name) &&
                (string.Compare(type, "JPG", true) == 0 || string.Compare(type, "PNG", true) == 0))
                {
                    //var webappRoot = Server.MapPath("Images/");
                    var webappRoot =
                        @"C:\Users\Ergün\Documents\Visual Studio 2012\Projects\KacincisinProject\KacincisinProject\Images\MathJaxImages\";
                    var fileName = webappRoot + name + "." + type;
                    using (var outputStream = new BinaryWriter(System.IO.File.Open(fileName, FileMode.Create)))
                    {
                        outputStream.Write(imageContent);
                        outputStream.Flush();
                    }

                    Response.ClearContent();
                    Response.Write("/Images/MathJaxImages/" + name + "." + type);
                    Response.End();
                }
            else
            {
                Response.ContentType = "image/jpeg";
                using (var os = Response.OutputStream)
                {
                    for (int i = 0; i < imageContent.Length; i++)
                        os.WriteByte(imageContent[i]);

                    os.Flush();
                    os.Close();
                }
            }
            return View();
        }
    }
}
